<?php

class fields_multiselect extends fields_select
{
   /**
    * Get HTML code for SELECT fields
    *
    * @param object $data
    * @return string
    */
   public function getFieldHTML($data)
   {
      $value = $data->{$this->alias}('source');
      $html = '';

      if(empty($this->values))
      {
         $html = '<span class="warn">'. gettext::translate('meccano', 'no_langvars') . '</span>';
      } else
      {
         $html .= '<ul class="multiselect">';
         foreach($this->values AS $k=>$v)
         {
            $html .= '<li><input type="checkbox" name="f['. $this->alias .'][]"';
            $html .= ' value="'. $k .'" id="f_'. $this->alias .'_'. $k .'"';
            if(in_array($k, (array)$value)) $html .= ' checked="checked"';
            $html .= ' /><label for="f_'. $this->alias .'_'. $k .'"> - '. $v .'</label></li>';
         }
         $html .= '</ul>';
      }

      return $html;
   }


   /**
    * Validate Input Data agains field type
    * @param mixed $value
    * @param object $dataObject
    * @return mixed
    */
   public function validateInput($value, $dataObject = NULL)
   {
      if(is_string($value)) $value = explode(',', $value);
      $value = array_intersect(array_keys($this->values), (array)$value);
      if(empty($value))
      {
         $this->value = $this->default;
      } else
      {
         $this->value = $value;
      }
      
      return $this->value;
   }


   /**
    * Normalize Value
    *
    * @param integer $value
    * @param string $lang
    */
   public function normalizeValue($value, $lang = null)
   {
      $this->src_value = array();

      if(!empty($this->values) && !empty($value))
      {
         $value = explode(',', $value);
         foreach($value AS $v)
         {
            if(isset($this->values[$v]))
            {
               $this->src_value[] = $v;
               $this->value[$v] = $this->values[$v];
            }
         }
      }
      
      return $this->value;
   }


   /**
    * Save value into DB
    * 
    * @param integer $lang
    * @return string
    */
   public function saveValue($lang = NULL)
   {
      if(property_exists($this, 'value') && !empty($this->value))
      {
         return join(',', $this->value);
      }

      return '';
   }
}